package comu.hnevc.zh.testdemo.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import comu.hnevc.zh.testdemo.MainActivity;
import comu.hnevc.zh.testdemo.R;
import comu.hnevc.zh.testdemo.base.BaseUrl;
import comu.hnevc.zh.testdemo.bean.BusBean;
import comu.hnevc.zh.testdemo.bean.BusCapacityBean;
import comu.hnevc.zh.testdemo.bean.BusStationInfoBean;

public class QueryBusFragment extends Fragment {
    private  static String TAG="QueryBusFragment";
    View view;
    private  String sharedPreferencesString;
    private TextView mOneTime1;
    private TextView mOneTime2;
    private TextView mOneDistance1;
    private TextView mOneDistance2;
    private  TextView mTwoTime1;
    private  TextView mTwoTime2;
    private TextView mTwoDistance1;
    private TextView mTwoDistance2;
    private Timer timer;
    int mCarCapacityNumbers;
    List<BusBean> busBeanList;
    private TextView allCapacityNum;
    private RequestQueue requestQueue;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       view=inflater.inflate(R.layout.query_bus_fragment,container,false);
       initView();
       return  view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        SharedPreferences sharedPreferences=getActivity().getSharedPreferences("data",Context.MODE_PRIVATE);
        sharedPreferencesString=sharedPreferences.getString("UserName","user1");
        requestQueue=((MainActivity)getActivity()).requestQueue;
        requestQueue.start();
        timer=((MainActivity)getActivity()).timer;
        TimerTask timerTask= new TimerTask() {
            @Override
            public void run() {
                initBusNow();
                getAllCapacity();

            }
        };
        timer.schedule(timerTask,0,3000);

    }
    private void initView() {

        mOneTime1=view.findViewById(R.id.quer_bus_fragment_time1_one);
        mOneTime2=view.findViewById(R.id.quer_bus_fragment_time1_two);
        mOneDistance1=view.findViewById(R.id.quer_bus_fragment_distance1_one);
        mOneDistance2=view.findViewById(R.id.quer_bus_fragment_distance1_two);
        mTwoTime1=view.findViewById(R.id.quer_bus_fragment_time2_one);
        mTwoTime2=view.findViewById(R.id.quer_bus_fragment_time2_two);

    }



    private void getAllCapacity() {
        mCarCapacityNumbers=0;
        busBeanList=new ArrayList<>();
        for (int i=1;i<=15;i++){
            JSONObject object=new JSONObject();
            try {
                object.put("UserName",sharedPreferencesString);
                object.put("BusId",i);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            final int finalI=i;
            JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, BaseUrl.BASEURL + BaseUrl.GetBusCapacity, object, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    Gson gson=new Gson();
                    BusCapacityBean busCapacityBean=gson.fromJson(jsonObject.toString(),BusCapacityBean.class);
                    BusBean busBean=new BusBean();
                    busBean.setBusnumber(finalI);
                    busBean.setOrdernumber(finalI);
                    busBean.setPeoplenumber(busCapacityBean.getBusCapacity());
                    busBeanList.add(busBean);

                    if (busBeanList.size()==15){
                        Collections.sort(busBeanList, new Comparator<BusBean>() {
                            @Override
                            public int compare(BusBean o1, BusBean o2) {
                                return o1.getOrdernumber()-o2.getOrdernumber();
                            }
                        });
                        allCapacityNum.setText("当前承载能力为："+mCarCapacityNumbers+"人");
                        mCarCapacityNumbers=0;
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Toast.makeText(getContext(),"ERROR",Toast.LENGTH_SHORT).show();

                }
            });
            requestQueue.add(request);
        }


    }
    private void initBusNow() {
        for (int i=1;i<=2;i++){
            final  JSONObject object=new JSONObject();
            try {
                object.put("UserName",sharedPreferencesString);
                object.put("BusStationId",i);

            } catch (JSONException e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST, BaseUrl.BASEURL + BaseUrl.GetBusStationInfo, object, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    int finalI=1;
                    try {
                        finalI=object.getInt("BusStationId");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
            Gson gson=new Gson();
                    BusStationInfoBean busStationInfoBean=gson.fromJson(jsonObject.toString(),BusStationInfoBean.class);
                    List<BusStationInfoBean.ROWSDETAILBean> rowsdetailBean=busStationInfoBean.getROWS_DETAIL();
                    Log.e(TAG,"onResponse:"+rowsdetailBean.toString());
                    for (int j=0;j<rowsdetailBean.size();j++){
                        if (finalI==1){
                            mOneTime1.setText((rowsdetailBean.get(0).getDistance()/10)/(20*1000/360)+"分钟到达");
                            mOneTime2.setText((rowsdetailBean.get(1).getDistance()/10)/(20*1000/360)+"分钟到达");
                            mOneDistance1.setText("距离:"+rowsdetailBean.get(0).getDistance()/10+"米");
                            mOneDistance2.setText("距离："+rowsdetailBean.get(1).getDistance()/10+"米");
                        }else if (finalI==2){
                            mTwoTime1.setText((rowsdetailBean.get(0).getDistance()/10)/(20*1000/360)+"分钟到达");
                            mTwoTime2.setText((rowsdetailBean.get(1).getDistance()/10)/(20*1000/360)+"分钟到达");
                            mTwoDistance1.setText("距离："+rowsdetailBean.get(0).getDistance()/10+"米");
                            mTwoDistance2.setText("距离："+rowsdetailBean.get(1).getDistance()/10+"米");
                        }


                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(getActivity(),"网络访问失败",Toast.LENGTH_SHORT).show();
                }
            });
            requestQueue.add(request);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
        requestQueue.stop();
    }
}
